package cn.iocoder.yudao.module.scrm.service.invoice;

import cn.iocoder.yudao.module.scrm.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.scrm.dal.mysql.order.OrderMapper;
import cn.iocoder.yudao.module.scrm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.scrm.util.CheckNoGeneratorUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.scrm.controller.admin.invoice.vo.*;
import cn.iocoder.yudao.module.scrm.dal.dataobject.invoice.InvoiceDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.scrm.dal.mysql.invoice.InvoiceMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.*;

/**
 * 发票 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class InvoiceServiceImpl implements InvoiceService {

    @Resource
    private InvoiceMapper invoiceMapper;
    @Resource
    private CheckNoGeneratorUtil checkNoGeneratorUtil;

    @Resource
    private OrderMapper orderMapper;

    @Override
    public Long createInvoice(InvoiceSaveReqVO createReqVO) {
        // 插入
        InvoiceDO invoice = BeanUtils.toBean(createReqVO, InvoiceDO.class);
        //invoice.setNo(checkNoGeneratorUtil.generateUniqueCheckNo(CrmBizTypeEnum.CRM_INVOICE.getType()));
        OrderDO orderDO = orderMapper.selectById(createReqVO.getOrderId());
        invoice.setNo(orderDO.getSystemNumber());
        invoice.setOwnerUserId(orderDO.getOwnerUserId());
        invoiceMapper.insert(invoice);
        // 返回
        return invoice.getId();
    }

    @Override
    public void updateInvoice(InvoiceSaveReqVO updateReqVO) {
        // 校验存在
        validateInvoiceExists(updateReqVO.getId());
        // 更新
        InvoiceDO updateObj = BeanUtils.toBean(updateReqVO, InvoiceDO.class);
        invoiceMapper.updateById(updateObj);
    }

    @Override
    public void deleteInvoice(Long id) {
        // 校验存在
        validateInvoiceExists(id);
        // 删除
        invoiceMapper.deleteById(id);
    }

    private void validateInvoiceExists(Long id) {
        if (invoiceMapper.selectById(id) == null) {
            throw exception(INVOICE_NOT_EXISTS);
        }
    }

    @Override
    public InvoiceDO getInvoice(Long id) {
        return invoiceMapper.selectById(id);
    }

    @Override
    public PageResult<InvoiceDO> getInvoicePage(InvoicePageReqVO pageReqVO) {
        return invoiceMapper.selectPage(pageReqVO);
    }

}